package com.google.code.yargon.ui.component;

import java.util.Calendar;
import java.util.LinkedList;

import com.google.code.yargon.ui.RenderEngine;

public class MessageComponent extends BufferedComponent {
	
	private static int lineNo = 0;
	private int bufferSize = 100;
	private int bufferShow = 5;
	private LinkedList<String> messageBuffer;
	
	/**
	 * 
	 */
	public MessageComponent(int x, int y, int w, int h, float alpha) {
		super(x, y, w, h, alpha);
		messageBuffer = new LinkedList<String>();
	} 
	
	/**
	 * Add a new message to the front of the message buffer. If the buffer reaches it's limit, remove message from the end.
	 * 
	 * @param message
	 */
	public void addMessage(String message) {
		
		Calendar c = Calendar.getInstance();
		String timeStamp = "[" + c.get(Calendar.HOUR_OF_DAY) + ":" + c.get(Calendar.MINUTE) + "] ";
		
		messageBuffer.addFirst(timeStamp + message);
		if(messageBuffer.size() > bufferSize) {
			messageBuffer.removeLast();
		}
		
		// Reset scroll to the first (newest) message when a new message is added
		lineNo = 0;
		setUpdated(true);
	}
	
	@Override
	protected void render() {	
		for(int i = 0; i < bufferShow; i++) {
			try {
				RenderEngine.renderText(RenderEngine.FONT_DEFAULT, messageBuffer.get(i + lineNo), 0, i * 14, false);
			} catch(Exception e) {
				// Array out of bounds ignored, happens when message buffer is still empty
			}
		}
		
		String pinned = "o";
		if(! this.isMovable()) {
			pinned = "x";
		}
		RenderEngine.renderText(RenderEngine.FONT_DEFAULT, pinned, getWidth() - 12, getHeight() - 12, false);
		RenderEngine.renderText(RenderEngine.FONT_DEFAULT, ">", getWidth() - 12, getHeight() - 26, false);
		RenderEngine.renderText(RenderEngine.FONT_DEFAULT, "<", getWidth() - 12, 2, false); 
	}
	
	@Override
	protected void update() {
		// Nothing to update
	}
	
	@Override
	protected void onClick(String id) {
		if(id.matches("scrolldown") && lineNo > 0) {
			lineNo--;
			setUpdated(true);
		}
		else if(id.matches("scrollup") && lineNo < messageBuffer.size() - bufferShow) {
			lineNo++;
			setUpdated(true);
		} 
		else if(id.matches("pinned")) {
			if(this.isMovable()) {
				this.setMovable(false);
			} else {
				this.setMovable(true);
			}
			setUpdated(true);
		}
	}
}
